<?php
App::uses('AppController', 'Controller');
class ClientsController extends AppController 
{
	public $uses = array('Clients');
 	
	public $components = array('Paginator');
	public function index() 
	{	
		
		
		$this->set("title_for_layout",'Clients');
		$pagination_settings= array();
		if(isset($this->data['keyword'])){
			$keyword = $this->data['keyword'];
			$pagination_settings['conditions']= array('Clients.dni LIKE' => "$keyword%");			
		}

		$pagination_settings['limit'] =30;
		$this->Paginator->settings =$pagination_settings;
	    $clients = $this->Paginator->paginate('Clients');
		$this->set('data',$clients);	

			
	}	

	public function add()
	{
		
		if (!empty($this->data)){
			$this->Clients->set($this->data);
			if($this->Clients->validates()){
				if($this->Clients->save($this->data)){
					$this->redirect('/clients');
				}
				/*else{
					$errors = $this->Clients->invalidFields();
					var_dump($errors);
					$this->Session->setFlash(__("Some Error", true), 'flash', array('class' => 'alert alert-error'));
				}*/
			}
			else{
				$errors = $this->Clients->validationErrors;
				//var_dump($errors);
				$this->Session->setFlash(__("Error", true), 'flash', array('class' => 'alert alert-error'));
			}	
		}
		
	}
	public function edit($id) {

        if (!empty($this->data)){
        	$this->Clients->id = $id;
            if ($this->Clients->save($this->data)) {
                $this->Session->setFlash('Cliente Actualizado.', 'flash', array('class' => 'thrill'));
                $this->redirect('/clients');
            }
        }
        else {
            $this->request->data = $this->Clients->findById($id);
        }
    }
	public function history($id){

		$client = $this->Clients->findById($id);
		//var_dump($client);
		$this->set("title_for_layout",'Historial Cliente: '.$client['Clients']['first_name']." ".$client['Clients']['last_name']);
		$this->set("client",$client);
		
	}

	public function get_data($id){
		$this->layout=false;
		$this->render(false);

		$data =  $this->Clients->findById($id);
		//var_dump($client);
		echo json_encode($data['Clients']);
	}

	public function delete(){
		$this->layout=false;
		$this->render(false);
		$this->Clients->delete($this->request->data('ids'));
		echo json_encode(true);
	}
}
